package com.haiberg.framework.dao.impl;

import com.haiberg.framework.dao.ICommonDao;
import org.apache.log4j.Logger;
import org.springframework.orm.hibernate4.SessionFactoryUtils;
import org.springframework.orm.hibernate4.support.HibernateDaoSupport;
import org.springframework.stereotype.Repository;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
@Repository("commonDao")
public class CommonDao extends HibernateDaoSupport implements ICommonDao{
	
	private static final Logger log = Logger.getLogger(CommonDao.class);
	public long getNextval(String sequence) {
		// TODO Auto-generated method stub
		long counter = 0;
		Connection conn = null;
		Statement stmt = null;
		ResultSet rset = null;
		try {
			conn = SessionFactoryUtils.getDataSource(super.getSessionFactory()).getConnection();
			stmt = conn.createStatement();
			rset = stmt.executeQuery("select nextval('"+sequence+"') as count");
			if(rset.next())
			{
				counter = rset.getLong("count");
			}
			return counter;
		} catch (RuntimeException re) {
			log.error("find by property name failed", re);
			throw re;
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally
		{
			
			try {
				if (rset != null)
					rset.close();
				if (stmt != null)
					stmt.close();
				if (conn != null)
					conn.close();
			} catch (Exception e2) {
				log.error("close connection got problem!", e2);
				try {
					throw e2;
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		return 0;
	}
}
